const fs = require("fs");
const path = require("path");
const { mkdir } = require("./mkdir");

/**
 * 复制文件
 * @param {*} fromFileName
 * @param {*} toFileName
 * @returns
 */
exports.copy = function (fromFileName, toFileName) {
  return new Promise(async (resolve, reject) => {
    // 创建目录
    let dirname = path.dirname(toFileName);
    await mkdir(dirname);
    const rs = fs.createReadStream(fromFileName, {
      autoClose: true,
      highWaterMark: 64 * 1024 * 1024,
      flags: "r",
    });
    const ws = fs.createWriteStream(toFileName, {
      flags: "a",
      highWaterMark: 16 * 1024 * 1024,
      autoClose: true,
    });
    rs.on("data", (chunk) => {
      ws.write(chunk);
    });

    rs.on("end", () => {
      resolve();
      //   console.log(`文件复制成功：${toFileName}`);
    });
    rs.on("error", (error) => {
      reject(error);
    });
  });
};
